<?php

namespace App\Store\Controllers\Goods;

use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Goods\GoodsStockList;
use App\Store\Services\Financial;
use App\Store\Services\Goods\Goods;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Common\Services\CommonExcelExport;
use App\Store\Models\Goods\GoodsTotalStockList;
use Maatwebsite\Excel\Facades\Excel;
use App\Store\Validate\Goods\GoodsTotalStockList as ValidateGoodsTotalStockList;
use Illuminate\Support\Facades\DB;

/**
 * 商品总库存列表
 */
class GoodsTotalStockListController extends Controller
{
    public function getlist(Request $request)
    {
        $list = GoodsTotalStockList::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    public function doexport(Request $request)
    {
        $list = GoodsTotalStockList::getList($request)['list'];
        $row = [
            ['table_header' => '商品库存信息'],
            [
                'storeinfo' => '所属门店',
                'goods_sn_code' => '条码',
                'goods_name' => '品名',
                'status' => '状态',
                'category_name' => '商品类别',
                'content' => '含量',
                'goods_craft_name' => '工艺',
                'goods_stone_name' => '石料材质',
                's_no' => '款号',
                'style_name' => '款式',
                'count' => '数量',
                'allot_count' => '调拨数量',
                'netglod_weight' => '金重',
                'netglod_weight_total' => '总金重',
                'piece_weight' => '重量',
                'piece_weight_total' => '总重量',
                'label_price' => '标签价',
                'brand_name' => '品牌',
                'gramprice_fee' => '克销工费',
                'piece_weight_total1' => '入库重量',
                'pieceprice_fee' => '件销工费',
                'costglod_price' => '成本金价',
                'costpiece_fee' => '按件成本工费',
                'costgram_fee' => '按克成本工费',
                'piececost_fee' => '单件成本',
                'piececost_fee_total' => '总成本',
                'goods_pricetype_name' => '价格类型',
                'cf_no' => '证书号', //Z
                'cf_no_gia' => 'GIA证书号',
                'main_stone_weigth' => '主石重',
                'main_stone_count' => '主石数',
                'other_stone_weigth' => '副石重',
                'other_stone_count' => '副石数',
                'c_no' => '圈号',
                'cf_fee' => '证书费',
                'color' => '颜色',
                'clarity' => '净度',
                'cut' => '切工',
                'startstoreinfo' => '初始入库门店',
                'stockin_at' => '入库时间',
                'create_at' => '创建时间',
            ]];

        $is_store_account = StoreCommon::getIsStoreAccount($request);
        if (!$is_store_account) {
            unset($row[0]['supply_name']);
            unset($row[0]['paymoney']);
            unset($row[0]['costglod_price']);
            unset($row[0]['total_fee']);
            unset($row[0]['piececost_fee']);
            unset($row[0]['piececost_fee_total']);
        }

        $exceldata = [];
        foreach ($list as $val) {
            $exceldata[] = [
                'storeinfo' => $val['storeinfo'] ? $val['storeinfo']['store_name'] : '',
                'goods_sn_code' => $val['goods_sn_code'],
                'goods_name' => $val['goods_name'],
                'status' => $val['count'] > 0 ? '在售' : '售出',
                'category_name' => $val['goods_category']['category_name'],
                'content' => $val['content'],
                'goods_craft_name' => isset($val['goods_craft']['craft_name']) ? $val['goods_craft']['craft_name'] : '',
                'goods_stone_name' => isset($val['goods_stone']['goods_stone_name']) ? $val['goods_stone']['goods_stone_name'] : '',
                's_no' => $val['s_no'],
                'style_name' => isset($val['goods_style']['style_name']) ? $val['goods_style']['style_name'] : '',
                'count' => $val['count'],
                'allot_count' => $val['allot_count'],
                'netglod_weight' => $val['netglod_weight'],
                'netglod_weight_total' => $val['netglod_weight'] * $val['count'],
                'piece_weight' => $val['piece_weight'],
                'piece_weight_total' => $val['piece_weight'] * $val['count'],
                'label_price' => $val['label_price'] / 100,
                'brand_name' => isset($val['goods_brand']['brand_name']) ? $val['goods_brand']['brand_name'] : '',
                'gramprice_fee' => $val['gramprice_fee'] / 100,
                'piece_weight_total1' => $val['piece_weight'] * $val['count'],
                'pieceprice_fee' => $val['pieceprice_fee'] / 100,
                'costglod_price' => $val['costglod_price'] / 100,
                'costpiece_fee' => $val['costpiece_fee'] / 100,
                'costgram_fee' => $val['costgram_fee'] / 100,
                'piececost_fee' => $val['piececost_fee'] / 100,
                'piececost_fee_total' => $val['piececost_fee'] / 100 * $val['count'],
                'goods_pricetype_name' => isset($val['goods_pricetype']['goods_pricetype_name']) ? $val['goods_pricetype']['goods_pricetype_name'] : '',
                'cf_no' => $val['cf_no'],
                'cf_no_gia' => $val['cf_no_gia'],
                'main_stone_weigth' => $val['main_stone_weigth'],
                'main_stone_count' => $val['main_stone_count'],
                'other_stone_weigth' => $val['other_stone_weigth'],
                'other_stone_count' => $val['other_stone_count'],
                'c_no' => $val['c_no'],
                'cf_fee' => $val['cf_fee'] / 100,
                'color' => $val['color'],
                'clarity' => $val['clarity'],
                'cut' => $val['cut'],
                'startstoreinfo' => $val['startstoreinfo'] ? $val['startstoreinfo']['store_name'] : '',
                'stockin_at' => date('Y-m-d', $val['stockin_at']),
                'create_at' => date('Y-m-d', $val['create_at']),
            ];
        }

        $filename = '商品库存信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    /**
     * 编辑
     */
    public function dopostedit(Request $request)
    {
        $req_data = $request->only(['id', 'return_supply_id', 'bank_card_number', 'paymoney', 'subject_id']);
        $Validate = new ValidateGoodsTotalStockList('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        GoodsTotalStockList::where('id', $req_data['id'])->update([
            'return_supply_id' => $req_data['return_supply_id'],
            'bank_card_number' => $req_data['bank_card_number'],
            'paymoney' => $req_data['paymoney'],
            'subject_id' => $req_data['subject_id'],
            'status' => 2
        ]);

        $info = GoodsTotalStockList::where('id', $req_data['id'])->first()->toArray();
        Financial::createMoneyLogByTotalstockin($cp_id, $info['store_id'], $req_data['paymoney'], $info['goods_sn_code'], $req_data['subject_id']);
        return response()->json(['code' => '000', 'msg' => '处理成功']);
    }

    /**
     * 详情
     */
    public function getone(Request $request)
    {
        $one = GoodsTotalStockList::getOne($request);
        if ($one) $one = $one->toArray();
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $one]);
    }

    /**
     * 上柜
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function oncounter(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $list = GoodsTotalStockList::query()
            ->where('cp_id', $cp_id)
            ->where('is_del', 1)
            ->whereIn('id', $request['ids'])
            ->get()
            ->toArray();
        if (!$list) {
            return response()->json(['code' => '000', 'msg' => '没有数据可上柜']);
        }

        //删除 返厂库存表 总件重 总金重 数量，追加到 商品库存表
        DB::beginTransaction();
        try {
            foreach ($list as $item) {
                if ($item['count'] > 0) {
                    $stock = GoodsStockList::query()->where([
                        'cp_id' => $item['cp_id'],
                        'store_id' => $item['store_id'],
                        'goods_sn_code' => $item['goods_sn_code'],
                        'is_del' => 1
                    ])->first();
                    if (empty($stock)) {
                        return response()->json(['code' => '001', 'msg' => '商品不存在']);
                    }

                    $stock = $stock->toArray();

                    $category =GoodsCategory::query()
                        ->where('cp_id', $cp_id)
                        ->where('is_del', 1)
                        ->where('id',$stock['goods_category_id'])
                        ->first();

                    if (empty($category)) {
                        return response()->json(['code' => '001', 'msg' => '商品类别不存在']);
                    }
                    $category =$category->toArray();


                    list($total_cost_fee,$costglod_price,$piececost_fee)=(new Goods())->incrTotalCost($stock,$item,$category['is_gram']);


                    $stock['count'] = $item['count'] + $stock['count'];
                    $stock['total_piece_weight'] = $item['total_piece_weight'] + $stock['total_piece_weight'];
                    $stock['total_netglod_weight'] = $item['total_netglod_weight'] + $stock['total_netglod_weight'];

                    //$total_cost_fee =(new Goods())->computeOriginalTotalCost($stock,$category['is_gram']);

                    $stockData['count'] =$stock['count'];
                    $stockData['total_piece_weight'] =$stock['total_piece_weight'];
                    $stockData['total_netglod_weight'] =$stock['total_netglod_weight'];
                    $stockData['total_cost_fee']=$total_cost_fee;
                    $stockData['costglod_price']=$costglod_price;
                    $stockData['piececost_fee']=$piececost_fee;


                    GoodsStockList::where('id', $stock['id'])->where('is_del',1)->update($stockData);

                    $update = [
                        'count' => 0,
                        'total_piece_weight' => 0,
                        'total_netglod_weight' => 0,
                        'status' => 3,
                        'total_cost_fee'=>0
                    ];
                    GoodsTotalStockList::where('id', $item['id'])->update($update);

                }
            }

            DB::commit();
            return response()->json(['code' => '000', 'msg' => '操作成功']);

        } catch (\Exception $e) {
            DB::rollBack();
            info('返厂上柜失败' . $e->getMessage() . $e->getLine());
            return response()->json(['code' => '001', 'msg' => '操作失败' . $e->getMessage()]);
        }
    }
}
